<?php
namespace Common\Model;
use Think\Model;
use Think\Exception;

// use Admin\Model\Users;

class ScoreTranModel extends Model {
  protected $error = null;
  protected $msg   = '';

    //积分异动操作方法
    /*
     * $busid:异动类型
     * $uid:用户id
     * $unick:用户名
     * $aid: 账户ID,留空则取默认账户
     * $type: -1:减; 1加
     * $money: 金额
     * $opid: 经办人
     * $channel: 通道
     * $orderId: 订单id
     * $memo: 备注
     * $source: 来源id,用于计算收益来源
     * $sourceUser: 来源,同上
     */
    public function tran($busid, $uid, $type, $score, $memo = '', $opid = '', $channel = 0, $orderId = '',  $source = '', $sourceUser = ''){

      if (empty($uid) || empty($busid)) {
        $this->error = -10;
        return false;
      }

      if (empty($type)) {
        $this->error = -11;
        return false;
      }

      $userData = D('Admin/Users')->getById($uid);

      if (empty($userData)) {
        $this->error = -14;
        return false;
      }

      if ($userData['status'] != 1) {
        $this->error = -15;
        return false;
      }

        // 判断crc
      if (!$this->checAccountkCRC($userData)) {
        $this->error = -12;
        return false;
      }

        //得到本次变化后的账户积分
      $userData['user_points'] = $userData['user_points'] + $score * $type;

      if(($userData['user_points'] < 0) || ($score < 0.01)){
        //如果本次变动后的账户积分小于0或者变动金额小于等于零//返回错误
        $this->error = -13;
        return false;
      }

      $userData['score_crc'] = $this->getAccountCRC($userData);

      $data = array(
        'id'         => $lastId,
        'uid'        => $uid,
        'uname'      => $userData['user_name'],
        'businessId' => $busid,
        'type'       => $type,
        'score'      => $score,
        'balance'    => $userData['user_points'],
        'memo'       => $memo,
        'operId'     => $opid,
        'createtime' => getModeltime(),
        'orderId'    => $orderId,
        'source'     => $source,
        'sourceUser' => $sourceUser
      );

      $lastId = getTimeMarkID();

      $model = new Model();

      try{
        $model->startTrans();

        $newUserData = array(
          'user_points' => $userData['user_points'],
          'score_crc'   => $userData['score_crc'],
        );

        $userInfoSaveRes = $model->table('__USERS__')->data($userData)->where(array('user_id'=>$userData['user_id']))->save();

        if (!$userInfoSaveRes) {
          throw new Exception("修改用户信息修改失败", -21);
        }

        $addLogRes = $model->table('__SCORE_TRAN__')->data($data)->add();

        if (!$addLogRes) {
          throw new Exception("添加异动记录失败", -22);
        }

        $model->commit();
        addlog('修改用户积分' . $uid, '', $userData);
        return true;
      }catch(Exception $e){
        $model->rollback();
        $this->error = $e->getCode();
        $this->msg   = $e->getMessage();
        return false;
      }
    }

    public function getAccountCRC($params){
      $str = $params['user_id']
      .$params['user_points']
         // .ROUND($params['a_freeMoney']*100)
         // .ROUND($params['frozenMoney']*100)
         // .ROUND($params['score']*1000)
      .$params['user_type'];

      return MD5(SHA1($str) . '@EC$^3^&3!#S$9%096%$$^&&le2g3*4H$%#$');

    }

     //加密异动记录,防止篡改
    private function md5Trans($p) {
      $string = implode('@!dE4', array_values($p));
      return MD5(SHA1($string) . $this->crcSalt);
    }

    //检查crc校验数据是否正确
    private function checAccountkCRC($params) {

      if($this->getAccountCRC($params) === $params['score_crc']){
        return true;
      }

      //crc错误,冻结用户
      D('Admin/Users')->freezeUser($params['user_id']);
      return false;
    }

    public function getError(){
      return $this->error;
    }

  }
